package com.gap.dam.module.business.category;

import com.gap.dam.common.base.ResponseDTO;
import com.gap.dam.module.business.category.dao.CategoryDao;
import com.gap.dam.module.business.category.domain.constant.CategoryResponseCodeConst;
import com.gap.dam.module.business.category.domain.dto.CategoryAddDTO;
import com.gap.dam.module.business.category.domain.dto.CategoryDTO;
import com.gap.dam.module.business.category.domain.dto.CategoryUpdateDTO;
import com.gap.dam.module.business.category.domain.entity.CategoryEntity;
import com.gap.dam.module.business.category.domain.vo.CategoryVO;
import com.gap.dam.util.BeanUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    /**
     * 查询Category，并构建树形结构返回
     * @return
     */
    public ResponseDTO<List<CategoryVO>> queryAll() {
        List<CategoryEntity> categoryEntityList = categoryDao.queryAll();
        List<CategoryVO> categoryVOList = BeanUtil.copyList(categoryEntityList, CategoryVO.class);
        List<CategoryVO> result = this.buildTree(categoryVOList);
        return ResponseDTO.succData(result);
    }

    /**
     * 查询Category，不构建树形结构返回
     * @return
     */
    public ResponseDTO<List<CategoryVO>> queryAllWithoutTree() {
        List<CategoryEntity> categoryEntityList = categoryDao.queryAll();
        List<CategoryVO> categoryVOList = BeanUtil.copyList(categoryEntityList, CategoryVO.class);
        return ResponseDTO.succData(categoryVOList);
    }

    /**
     * 查询Category
     * @return
     */
    public ResponseDTO<List<CategoryDTO>> queryAllWithoutTree2() {
        List<CategoryEntity> categoryEntityList = categoryDao.queryAll();
        List<CategoryDTO> categoryDTOList = BeanUtil.copyList(categoryEntityList, CategoryDTO.class);
        return ResponseDTO.succData(categoryDTOList);
    }


    /**
     * 构建目录树
     * @param categoryVOList
     * @return
     */
    public List<CategoryVO> buildTree(List<CategoryVO> categoryVOList) {
        if(CollectionUtils.isEmpty(categoryVOList)){
            return Lists.newArrayList();
        }
        List<CategoryVO> list = categoryVOList.stream().filter(e -> e.getParentId() == null || e.getParentId() == 0).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(list)){
            return Lists.newArrayList();
        }
        this.buildTree(list, categoryVOList);
        return list;
    }

    private void buildTree(List<CategoryVO> nodeList,List<CategoryVO> categoryVOList){
        int nodeSize = nodeList.size();
        for(int i =0 ;i< nodeSize;i++) {
            int preIndex = i-1;
            int nextIndex = i+1;
            CategoryVO node = nodeList.get(i);
            if(preIndex>-1){
                node.setPreId(nodeList.get(preIndex).getId());
            }
            if(nextIndex<nodeSize){
                node.setNextId(nodeList.get(nextIndex).getId());
            }
            buildTree(node, categoryVOList);
        }
    }

    private void buildTree(CategoryVO node, List<CategoryVO> categoryVOList) {
        List<CategoryVO> children = getChildren(node, categoryVOList);
        if (CollectionUtils.isNotEmpty(children)) {
            node.setChildren(children);
            children.forEach(e -> {
                e.setParent(node);
            });
            this.buildTree(children,categoryVOList);
        }
    }

    private List<CategoryVO> getChildren(CategoryVO node, List<CategoryVO> categoryVOList) {
        Long parentId = node.getId();
        return categoryVOList.stream().filter(e -> parentId.equals(e.getParentId())).collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<Long> addCategory(CategoryAddDTO categoryAddDTO) {
        if (categoryAddDTO.getParentId() == null)
            categoryAddDTO.setParentId(0L); // 默认设置为根节点
        CategoryEntity categoryEntity = BeanUtil.copy(categoryAddDTO, CategoryEntity.class);
        categoryDao.insert(categoryEntity);
        return ResponseDTO.succData(categoryEntity.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> updateCategory(CategoryUpdateDTO categoryUpdateDTO) {
        CategoryEntity categoryEntity = categoryDao.selectById(categoryUpdateDTO.getId());
        if (null == categoryEntity) {
            return ResponseDTO.wrap(CategoryResponseCodeConst.CATEGORY_NOT_EXISTS);
        }

        categoryEntity = BeanUtil.copy(categoryUpdateDTO, CategoryEntity.class);
        categoryDao.updateById(categoryEntity);
        return ResponseDTO.succ();
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> updateCategoryPictureUrl(Long id, String pictureUrl) {
        CategoryEntity categoryEntity = categoryDao.selectById(id);
        categoryEntity.setPictureUrl(pictureUrl);
        categoryDao.updateById(categoryEntity);
        return ResponseDTO.succ();
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> deleteById(Long id) {
        categoryDao.deleteById(id);
        return ResponseDTO.succ();
    }

}
